<template>
    <div class="debate-container">
      <!-- 固定标题栏 -->
      <div class="fixed-header">
        <h3>你的立场: {{ selectedStance }}</h3>
      </div>
  
      <!-- 可滚动内容区 -->
      <div class="scroll-content">
        <!-- <div class="arguments-grid"> -->
         
          <div class="ai-arguments">
            <div class="arguments-list">
              <div v-for="(round, index) in debateRounds" 
                   :key="index" 
                   class="arguments-grid"
                   >
                <div class="argument-card ai-card">
                  <p style="text-align: left;">{{ 'Round'+(index+1)+' AI: ' }}</p>
                  <span v-if="round.ai==='generating'">█</span>
                  <p>{{ round.ai }}</p>
                </div>
                <div class="argument-card user-card" v-if="round.user">
                  <p style="text-align: left;">{{ 'Round'+(index+1)+' 用户: ' }}</p>
                  <p>{{ round.user }}</p>
                </div>
              </div>
              
              <!-- <div v-if="isAIResponding" class="argument-card ai-card">
                <p style="text-align: left;">{{ 'Round'+(aiArguments.length + 1)+' ai: ' }}</p>
                <p>{{ currentAIResponse }}</p>
              </div> -->
            </div>
          </div>
  
          
          <!-- <div class="user-arguments">
            <div class="arguments-list">
              <div v-for="(arg, index) in userArguments" 
                   :key="'user'+index" 
                   class="argument-card user-card">
                <p style="text-align: left;">{{ 'Round'+(index+1)+' 用户: ' }}</p>
                <p>{{ arg }}</p>
              </div>
            </div>
          </div> -->
        <!-- </div> -->
        <!-- <div class="debate-flow">
            <div 
              v-for="(round, index) in debateRounds" 
              :key="index"
              class="round-container"
            >
              <div class="ai-message">
                <div class="round-label">Round{{ index + 1 }} AI:</div>
                <div class="message-bubble">
                  <span v-if="round.ai === 'generating'">█</span>
                  {{ round.ai }}
                </div>
              </div>
              <div 
                v-if="round.user" 
                class="user-message"
              >
                <div class="round-label">Round{{ index + 1 }} 用户:</div>
                <div class="message-bubble">{{ round.user }}</div>
              </div>
            </div>
          </div> -->
      </div>
  
      <!-- 固定输入框 -->
      <div class="fixed-footer">
        <div class="input-section">
          <el-input
            v-model="newArgument"
            :placeholder=inputHolder
            class="custom-input"
          />
          <el-button 
            type="primary" 
            class="submit-btn"
            :disabled="isAIResponding"
            @click="submitArgument"
          >
            发送
          </el-button>
        </div>
      </div>
    </div>
  </template>

<script setup>
import { useRoute } from 'vue-router'
import { onMounted, watchEffect } from 'vue'
import { ref, computed } from 'vue'
import { error } from "../tools/messageBox"
import {useAppStore} from "../stores/app"
import {createSession, getAIResponse,sendUserResponse} from "../services/debateServ"
const store=useAppStore()
const route = useRoute()

// 响应式数据（保持与图片1中的"Your Stance: Pro"对应）
const selectedStance = ref('正方') // 用户选择的立场
const debatePrompt = ref('')//论点

// 监听路由参数变化
watchEffect(() => {
  // 从路由参数获取值（带类型转换）
  selectedStance.value = route.query.selectedStance || '正方'
  debatePrompt.value = route.query.debatePrompt || ''
})

// 辩论流程数据
const debateRounds = ref([])
const currentRound = ref(0)

const inputHolder= ref('AI正在输入中')
const isAIResponding=ref(true)//AI正在输入，用户不可输入
const sessionId=ref(-1)//此次辩论会话的ID
// 组件挂载时启动辩论
onMounted(() => {
  const res1=createSession({id:store.$state.userInfo.id,//用户ID
                            userPosition:selectedStance,//用户立场
                            debatePrompt:debatePrompt//论点
                          })
  sessionId.value=res1.id
  initDebate()
})
const newArgument = ref('')
// 初始化辩论流程
const initDebate = () => {
  debateRounds.value = [{
    ai: 'generating',  // 特殊标识表示生成中
    user: null
  }]
  currentRound.value = 0
  generateAIResponse()
}
// 生成AI响应
const generateAIResponse = async () => {
  isAIResponding.value = true
  inputHolder.value = 'AI正在思考中...'
  
  // 模拟WebSocket连接
  const mockResponse = await simulateAIResponse()
  let displayedText = ''
  
  const interval = setInterval(() => {
    if (displayedText.length < mockResponse.length) {
      displayedText += mockResponse[displayedText.length]
      updateAIRound(displayedText)
    } else {
      clearInterval(interval)
      finalizeAIRound(mockResponse)
      inputHolder.value = '输入你的观点...'
      isAIResponding.value = false
    }
  }, 50)
}

// 更新AI回答（实时效果）
const updateAIRound = (text) => {
  debateRounds.value[currentRound.value].ai = text
}
// 完成AI回答
const finalizeAIRound = (finalText) => {
  debateRounds.value[currentRound.value].ai = finalText
}
// 用户提交观点
const submitArgument = async () => {
  if (!newArgument.value.trim()) return
  
  // 更新用户回合
  debateRounds.value[currentRound.value].user = newArgument.value.trim()
  const res=sendUserResponse({
    userId:store.$state.userInfo.id,
    sessionId:sessionId,
    userResponse:newArgument.value
  })
  if(res.code!=200)
    error('出现异常问题')
  newArgument.value = ''
  // 准备下一回合
  debateRounds.value.push({
    ai: 'generating',
    user: null
  })
  currentRound.value++
  
  // 触发AI响应
  await generateAIResponse()
}
// 模拟AI生成（整合辩论参数）
const simulateAIResponse =async ()=>{
  const res=getAIResponse({userId:store.$state.userInfo.id,
                           sessionId:sessionId
                          })
  if(res.code!=200)
    error('AI回答失败')
  return (await res).data
}
// const simulateAIResponse = async () => {
//   // 根据立场和提示生成响应
//   const stanceMap = {
//     正方: [
//       "人工智能将显著提高医疗诊断准确性，例如...",
//       "自动化系统可以有效优化交通流量，根据...",
//       "机器学习算法能够降低30%以上的能源消耗..."
//     ],
//     反方: [
//       "过度依赖AI可能导致医疗责任界定困难，例如...",
//       "交通自动化系统存在重大安全隐患，如...",
//       "算法优化带来的能源节省可能被算力消耗抵消..."
//     ]
//   }
  
//   const promptKeywords = debatePrompt.value.match(/[\u4e00-\u9fa5a-zA-Z0-9]+/g) || []
//   const baseResponse = stanceMap[selectedStance.value][currentRound.value % 3]
  
//   return promptKeywords.length > 0 
//     ? `${baseResponse}（基于 ${promptKeywords.join('、')}）`
//     : baseResponse
// }

// const userArguments = ref([
//   '1','2'
// ])
// const aiArguments = ref([
//   '1','2'
// ])


</script>
  
  <style scoped>
  /* 基础容器 */
  .debate-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background: #f9f9fb; 
    position: relative;
  }
  
  /* 固定标题栏 */
  .fixed-header {
    position: sticky;
    top: 0;
    z-index: 1000;
    background: #f9f9fb;
    padding: 16px 24px;
    border-bottom: 1px solid #333;
    
    h3 {
      color: #4386df;
      margin: 0;
      font-size: 18px;
    }
  }
  
  /* 可滚动内容区 */
  .scroll-content {
    flex: 1;
    overflow-y: auto;
    padding: 20px 24px 80px; /* 底部留出输入框空间 */
    background: #f9f9fb;
  }
  
  /* 双栏布局 */
  .arguments-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    min-height: 300px; /* 动态高度计算 */
  }
  
  /* 论点卡片样式 */
  .argument-card {
    background: rgba(255, 255, 255, 0.05);
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 12px;
    border: 1px solid #333;
    height: 300px;
    
    p {
      color: #333;
      line-height: 1.6;
      margin: 0;
      font-size: 14px;
    }
  }
  
  /* AI卡片特殊样式 */
  .ai-card {
    border-left: 3px solid #409EFF; /* 蓝色左侧边框 */
  }
  
  /* 用户卡片特殊样式 */
  .user-card {
    border-left: 3px solid #E6A23C; /* 橙色左侧边框 */
  }
  
  /* 固定底部输入 */
  .fixed-footer {
    position: sticky;
    bottom: 0;
    z-index: 1000;
    background: #f9f9fb;
    padding: 16px 24px;
    border-top: 1px solid #f9f9fb;
  }
  
  /* 输入区域样式 */
  .input-section {
    display: flex;
    gap: 12px;
    max-width: 800px;
    margin: 0 auto;
  }
  
  .custom-input {
    flex: 1;
    
    :deep(.el-input__inner) {
      height: 40px;
      border-radius: 20px;
      background: #fff;
      border: none;
      padding: 0 20px;
    }
  }
  
  .submit-btn {
    width: 120px;
    border-radius: 20px;
    background: #409EFF;
    border: none;
    transition: all 0.3s;
  }
  </style>